use strict;
use warnings;

my $inputFilename = shift @ARGV;
my $outputFilename = "$inputFilename.queries";

open (INF, "< $inputFilename") or 
  die "File cannot be opened for reading - $inputFilename";
open (OUTF, "> $outputFilename") or 
  die "File cannot be opened for writing - $outputFilename";

my $line;

while ($line = <INF>) {
  &trimWhitespaceBothSides(\$line);
  &reliablyRemoveEol(\$line);
  &removeRepeatedWhitespace(\$line);

  if ($line =~ /(\d+):(\d):(.*)$/) {
    print OUTF "query-$1-$2\t$3\n";
  }
}

close(INF);
close(OUTF);

sub trimWhitespaceBothSides(\$) {
  my ($stringRef) = @_;
    
  # remove leading whitespace
  $$stringRef =~ s/^\s*//;
  # remove trailing whitespace
  $$stringRef =~ s/\s*$//;
}

sub reliablyRemoveEol(\$) {
  my ($stringRef) = @_;
    
  my $char_0D = chr(0x0D);
  my $char_0A = chr(0x0A);

  # globally remove all end-of-line chars
  $$stringRef =~ s/$char_0D/ /g;
  $$stringRef =~ s/$char_0A/ /g;
}

sub removeRepeatedWhitespace(\$) {
  my ($stringRef) = @_;

  $$stringRef =~ s/\s+/ /g;
}

